package com.dudy.web.oa.leave;

import com.dudy.util.UserUtil;
import com.dudy.entity.Leave;
import com.dudy.service.oa.leave.LeaveManager;
import com.dudy.service.oa.leave.LeaveWorkflowService;
import com.dudy.util.Variable;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:wb-zhaojunwei@alibaba-inc.com">wb-zhaojunwei></a>
 * @version 1.0
 * @Description 普通请假单controller
 * @since 2016/3/10
 */
@Controller
@RequestMapping(value = "/oa/leave")
public class LeaveController {
    private static Logger logger = LoggerFactory.getLogger("error");
    @Resource
    private LeaveWorkflowService workflowService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private LeaveManager leaveManager;

    @RequestMapping(value = {"apply", ""})
    public String createForm(Model model) {
        model.addAttribute("leave", new Leave());
        return "/oa/leave/leaveApply";
    }

    @RequestMapping(value = "start", method = RequestMethod.POST)
    public String start(Leave leave, HttpSession session, RedirectAttributes redirectAttributes) {
        try {
            User user = UserUtil.getUserFromSession(session);
            if (user == null || StringUtils.isBlank(user.getId())) {
                return "redirect:/login?timeout=true";
            }
            leave.setUserId(user.getId());
            Map<String, Object> variables = new HashMap<String, Object>();
            ProcessInstance processInstance = workflowService.startWorkflow(leave, variables);
            redirectAttributes.addFlashAttribute("message", "流程已启动，流程ID：" + processInstance.getId());
        } catch (ActivitiException e) {
            if (e.getMessage().indexOf("no processes deployed with key") != -1) {
                logger.warn("没有部署流程!", e);
                redirectAttributes.addFlashAttribute("error", "没有部署流程，请在[工作流]->[流程管理]页面点击<重新部署流程>");
            } else {
                logger.error("启动请假流程失败：", e);
                redirectAttributes.addFlashAttribute("error", "系统内部错误！");
            }
        } catch (Exception e) {
            logger.error("启动请假流程失败：", e);
        }
        return "redirect:/oa/leave/apply";
    }

    /**
     * 任务列表
     */
    @RequestMapping(value = "list/task")
    public ModelAndView taskList(HttpSession session) {
        ModelAndView mav = new ModelAndView("/oa/leave/taskList");
        String userId = UserUtil.getUserFromSession(session).getId();
        List<Leave> leaves = workflowService.findTodoTasks(userId);
        mav.addObject("page", leaves);
        return mav;
    }

    /**
     * 读取运行中的流程实例
     *
     * @return
     */
    @RequestMapping(value = "list/running")
    public ModelAndView runningList() {
        ModelAndView mav = new ModelAndView("/oa/leave/running");
        List<Leave> lists = workflowService.findRunningProcessInstaces();
        mav.addObject("page", lists);
        return mav;
    }

    /**
     * 读取运行结束的流程实例
     *
     * @return
     */
    @RequestMapping(value = "list/finished")
    public ModelAndView finishedList() {
        ModelAndView mav = new ModelAndView("/oa/leave/finished");
        List<Leave> lists = workflowService.findFinishedProcessInstaces();
        mav.addObject("page", lists);
        return mav;
    }

    /**
     * 签收任务
     */
    @RequestMapping(value = "task/claim/{id}")
    public String claim(@PathVariable("id") String taskId, HttpSession session, RedirectAttributes redirectAttributes) {
        String userId = UserUtil.getUserFromSession(session).getId();
        taskService.claim(taskId, userId);
        redirectAttributes.addFlashAttribute("message", "任务已签收");
        return "redirect:/oa/leave/list/task";
    }

    /**
     * 读取详细数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "detail/{id}")
    @ResponseBody
    public Leave getLeave(@PathVariable("id") Long id) {
        Leave leave = leaveManager.getLeave(id);
        return leave;
    }

    /**
     * 读取详细数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "detail-with-vars/{id}/{taskId}")
    @ResponseBody
    public Leave getLeaveWithVars(@PathVariable("id") Long id, @PathVariable("taskId") String taskId) {
        Leave leave = leaveManager.getLeave(id);
        Map<String, Object> variables = taskService.getVariables(taskId);
        leave.setVariables(variables);
        return leave;
    }

    /**
     * 完成任务
     *
     * @param taskId
     * @return
     */
    @RequestMapping(value = "complete/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String complete(@PathVariable("id") String taskId, Variable var) {
        try {
            Map<String, Object> variables = var.getVariableMap();
//            if (variables.get("realityStartTime") !=null || variables.get("realityEndTime")!=null){
//                Leave leave = new Leave();
//                leave.setId();
//            }
            taskService.complete(taskId, variables);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }
}
